package com.yantong.controller.locallife;

import com.yantong.annotation.Log;
import com.yantong.constant.PayStatus;
import com.yantong.constant.TicketRange;
import com.yantong.constant.TicketType;
import com.yantong.controller.BaseController;
import com.yantong.exception.BDException;
import com.yantong.pojo.*;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 优惠券控制类
 *
 * @author kanghaixin
 * @date 2018/9/25.11:04
 */
@Controller
@RequestMapping("/promotion/ticket")
public class TicketController extends BaseController {

	private static final String prefix = "promotion/ticket";
	@Autowired
	private TicketService ticketService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	@Lazy
	private ProductCentreService productCentreService;
	@Autowired
	private ProductGradeService productGradeService;
	@Autowired
	private IndustryService industryService;
	@Autowired
	private IndustryBrandService industryBrandService;

	/**
	 * 优惠券列表
	 *
	 * @param model
	 * @return
	 */
	@RequiresPermissions("promotion:ticket:ticket")
	@GetMapping()
	public String tickets(Model model) {
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/tickets";
	}


	/**
	 * 优惠券列表数据
	 *
	 * @param queryItem
	 * @param centreId
	 * @param status
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("promotion:ticket:ticket")
	public PageUtils<Ticket> listTickets(String queryItem, Long centreId, Long teamId, Integer status, Integer activityType, Long activityId, Integer usableFlag, int offset, int limit) {
		if (centreId == null) {
			centreId = getUserCentreId();
		}
		if (teamId == null) {
			teamId = getUserTeamId();
		}
		return ticketService.listTickets(queryItem, centreId, teamId, status, activityType, activityId, usableFlag,offset, limit);
	}


	/**
	 * 优惠券列表数据
	 *
	 * @param queryItem
	 * @param centreId
	 * @param status
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listByFreecharge")
	@RequiresPermissions("promotion:ticket:ticket")
	public PageUtils<Ticket> listByFreecharge(String queryItem, Long centreId, Long teamId, Integer status, Integer activityType, Long activityId, int offset, int limit) {
		if (centreId == null) {
			centreId = getUserCentreId();
		}
		if (teamId == null) {
			teamId = getUserTeamId();
		}
		return ticketService.listByFreecharge(queryItem, centreId, teamId, status, activityType, activityId, offset, limit);
	}

	/**
	 * 优惠券新增页面
	 *
	 * @return
	 */
	@RequiresPermissions("promotion:ticket:add")
	@GetMapping("/add")
	public String add(Model model) {
		//商品品类
		List<ProductGrade> productGradeList = productGradeService.selectByAll();
		model.addAttribute("productGrades", productGradeList);
		//行业数据
		HashMap hashMap = new HashMap();
		hashMap.put("centreId", getUserCentreId());
		List<Industry> industryList = industryService.selectByList(hashMap);
		model.addAttribute("industrys", industryList);
		//行业品牌数据
		List<IndustryBrand> industryBrandList = industryBrandService.listByCentreId(hashMap);
		model.addAttribute("industryBrands", industryBrandList);

		model.addAttribute("types", TicketType.listTicketTypes());
		model.addAttribute("ranges", TicketRange.listTicketRanges());
		model.addAttribute("categoryList", categoryService.listCategorys(0L));
		model.addAllAttributes(getCentreIdModelInfo());
		model.addAllAttributes(getTeamIdModelInfo());
		//有值就是门店，没有就是商户
		model.addAttribute("team_id", getUser().getTeamId());
		return prefix + "/add";
	}

	/**
	 * 限制商品选择页面
	 *
	 * @param centreId
	 * @param model
	 * @return
	 */
	@GetMapping("/limitProduct")
	public String limitProduct(Long centreId, Long teamId, Model model) {
		model.addAttribute("centreId", centreId);
		model.addAttribute("teamId", teamId);
		return prefix + "/limitProduct";
	}

	/**
	 * 商品列表
	 *
	 * @param centreId
	 * @param productId
	 * @param title
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listLimitProducts")
	public PageUtils<ProductCentre> listLimitProducts(Long centreId, Long teamId, Long productId, String title, int offset, int limit) {
		if (centreId == null) {
			centreId = getUserCentreId();
		}
		if (teamId == null) {
			teamId = getUserTeamId();
		}
		return productCentreService.listByTitleAndId(productId, title, centreId, teamId, offset, limit);
	}

	/**
	 * 优惠券新增操作
	 *
	 * @param ticket
	 * @return
	 */
	@Log(module = "优惠券管理", operation = "新增")
	@ResponseBody
	@RequiresPermissions("promotion:ticket:add")
	@PostMapping("/save")
	public ResultVo save(Ticket ticket) {
		if (ticket == null) {
			return ResultVo.error();
		}
		if (ticket.getCentreId() == null) {
			ticket.setCentreId(getUserCentreId());
		}
		if (ticket.getTeamId() == null) {
			ticket.setTeamId(getUserTeamId());
		}
		ticket.setOperateId(getUserId());
		ticket.setOperateName(getNikeName());
		if (ticketService.saveTicket(ticket) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 优惠券编辑
	 *
	 * @param model
	 * @return
	 */
	@RequiresPermissions("promotion:ticket:edit")
	@GetMapping("/edit/{ticketId}")
	public String edit(Model model, @PathVariable Long ticketId) {
		//商品品类
		List<ProductGrade> productGradeList = productGradeService.selectByAll();
		model.addAttribute("productGrades", productGradeList);
		//行业数据
		HashMap hashMap = new HashMap();
		hashMap.put("centreId", getUserCentreId());
		List<Industry> industryList = industryService.selectByList(hashMap);
		model.addAttribute("industrys", industryList);
		//行业品牌数据
		List<IndustryBrand> industryBrandList = industryBrandService.listByCentreId(hashMap);
		model.addAttribute("industryBrands", industryBrandList);

		model.addAttribute("types", TicketType.listTicketTypes());
		model.addAttribute("ranges", TicketRange.listTicketRanges());
		model.addAllAttributes(getCentreIdModelInfo());
		model.addAttribute("categoryList", categoryService.listCategorys(0L, null, getUserCentreId(), getUserTeamId()));
		model.addAttribute("ticket", ticketService.getByKey(ticketId));
		//有值就是门店，没有就是商户
		model.addAttribute("team_id", getUser().getTeamId());
		return prefix + "/edit";
	}

	/**
	 * 优惠券编辑保存
	 *
	 * @param ticket
	 * @return
	 */
	@Log(module = "优惠券管理", operation = "编辑")
	@ResponseBody
	@PostMapping("/update")
	@RequiresPermissions("promotion:ticket:edit")
	public ResultVo updateTicket(Ticket ticket) {
		if (ticket == null || ticket.getId() == null) {
			return ResultVo.error();
		}
		Integer addNum = ticket.getAddNum();
		Ticket ticketExit = ticketService.getByKey(ticket.getId());
		if (ValidateUtil.isNotEmptyObjectOrString(addNum)) {
			if (addNum < 0) {
				throw new BDException("不允许将发券数量修改至小于之前的值!");
			} else {
				ticket.setTotal(ticketExit.getTotal() + addNum);
				ticket.setStock(ticketExit.getStock() + addNum);
			}
		}
		if (ticketService.updateTicket(ticket) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 删除优惠券
	 *
	 * @param ticketId
	 * @return
	 */
	@Log(module = "优惠券管理", operation = "删除")
	@ResponseBody
	@RequiresPermissions("promotion:ticket:remove")
	@PostMapping("/remove")
	public ResultVo remove(Long ticketId) {
		if (ticketId == null) {
			return ResultVo.error();
		}
		Ticket ticket = ticketService.getByKey(ticketId);
		ticket.setId(ticketId);
		ticket.setOperateName(getNikeName());
		ticket.setOperateId(getUserId());
		ticket.setDel(1);
		if (ticketService.updateTicket(ticket) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}


	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@Log(module = "优惠券管理", operation = "批量删除")
	@RequiresPermissions("promotion:ticket:remove")
	@PostMapping("/batchRemove")
	@ResponseBody
	public ResultVo batchRemove(@RequestParam("ids[]") Long[] ids) {
		if (ids == null || ids.length < 1) {
			return ResultVo.error();
		}
		for (Long id : ids) {
			Ticket ticket = ticketService.getByKey(id);
			ticket.setId(id);
			ticket.setOperateName(getNikeName());
			ticket.setOperateId(getUserId());
			ticket.setDel(1);
			if (ticketService.updateTicket(ticket) < 1) {
				return ResultVo.error();
			}
		}
		return ResultVo.ok();
	}


	/**
	 * 优惠券领用记录
	 *
	 * @param ticketId
	 * @return
	 */
	@RequiresPermissions("promotion:ticket:useRecord")
	@GetMapping("/ticketRecords/{ticketId}")
	public String ticketRecords(@PathVariable Long ticketId, Model model) {
		model.addAttribute("ticketId", ticketId);
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/ticketRecords";
	}


	/**
	 * 优惠券领用记录
	 *
	 * @return
	 */
	@RequiresPermissions("promotion:ticket:record")
	@GetMapping("/toTicketRecords")
	public String toTicketRecords(Model model) {
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/ticketRecords";
	}

	/**
	 * 优惠券领用记录
	 *
	 * @param centreId
	 * @param queryItem
	 * @param status
	 * @param ticketId
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listRecords")
	@RequiresPermissions("promotion:ticket:useRecord")
	public PageUtils<TicketRecord> listRecords(Long centreId, String queryItem, Integer status, Long ticketId, Long judge, int offset, int limit) {
		return ticketService.listRecords(centreId, queryItem, status, ticketId, judge, offset, limit);
	}

	/**
	 * 优惠券发放页面
	 *
	 * @param ticketId
	 * @param model
	 * @return
	 */
	@RequiresPermissions("promotion:ticket:send")
	@GetMapping("/send/{ticketId}")
	public String send(@PathVariable Long ticketId, Model model) {
		model.addAttribute("ticketId", ticketId);
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/send";
	}

	/**
	 * 选择会员
	 *
	 * @return
	 */
	@GetMapping("/selectMember")
	public String selectMember() {
		return prefix + "/selectMember";
	}

	/**
	 * 选择会员(多选)
	 *
	 * @param linkMember
	 * @return
	 */
	@GetMapping("/selectMembers")
	public String selectMembers(String linkMember, Model model) {
//		model.addAttribute("ticketId", ticketId);
		model.addAttribute("linkMember", linkMember);
		return prefix + "/selectMembers";
	}

	/**
	 * 优惠券发放
	 *
	 * @param record
	 * @return
	 */
	@Log(module = "优惠券管理", operation = "发放")
	@ResponseBody
	@RequiresPermissions("promotion:ticket:send")
	@PostMapping("/sendTicket")
	public ResultVo sendTicket(TicketRecord record, Long[] mids) {
		if (record == null) {
			return ResultVo.error();
		}
		if (record.getCentreId() == null) {
			record.setCentreId(getUserCentreId());
		}
		if (mids != null && mids.length > 0) {
			for (Long mid : mids) {
				record.setMid(mid);
				if (ticketService.sendTicket(record) < 1) {
					return ResultVo.error("部分会员优惠券因数量不足发放失败！");
				}
			}
		}
		return ResultVo.ok();
	}

	/**
	 * 优惠券发放(按站点发放)
	 *
	 * @param record
	 * @return
	 */
	@Log(module = "优惠券管理", operation = "按站点发放优惠券")
	@ResponseBody
	@RequiresPermissions("promotion:ticket:send")
	@PostMapping("/sendTicketAll")
	public ResultVo sendTicketAll(TicketRecord record) {
		if (record == null) {
			return ResultVo.error();
		}
		if (record.getCentreId() == null) {
			return ResultVo.error("站点不能为空,请选择站点！");
		}
		Long userCentreId = getUserCentreId();
		if (userCentreId != null && !userCentreId.equals(record.getCentreId())) {
//		if (userCentreId != null && userCentreId != record.getCentreId()) {
			return ResultVo.error("优惠券发放失败,用户异常！");
		}
		if (ticketService.sendTicketAll(record, userCentreId) < 1) {
			return ResultVo.error("优惠券发放失败！");
		}
		return ResultVo.ok();
	}

	/**
	 * 优惠券订单商品列表页面
	 *
	 * @param model
	 * @return
	 */

	@GetMapping("/toOrderProductPage")
	public String toOrderProductPage(Model model) {
		model.addAttribute("payStatusList", PayStatus.getPayStatusList());
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/ordproduct";
	}

	/**
	 * 记录失效
	 *
	 * @param recordId
	 * @return
	 */
	@ResponseBody
	@PostMapping("/disableRecord")
	@RequiresPermissions("promotion:ticket:disableRecord")
	public ResultVo diableRecord(Long recordId) {
		if (recordId == null) {
			return ResultVo.error();
		}
		if (ticketService.disableRecord(recordId) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 通兑券选择可使用的门店
	 */
	@GetMapping("/selectTeam")
	public String selectTeam(Model model, String ids, String names) {
		model.addAttribute("ids", ids);
		model.addAttribute("names",names);
		return prefix + "/selectTeam";
	}
}
